# -*- coding: utf-8 -*-
# @Time    : 2021/4/9 18:56
# @Author  : xxue
# @Email   : x_xue1212@163.com
# @File    : 4-9python.py
# @Software: PyCharm

#######1
# ip存储与读取文件统计ip频率（京东二面题）
# 生成一个大文件ips.txt,要求120000行，每行随机为172.25.254.0/24段的ip
# 读取ips.txt文件统计这个文件种ip出现频率前10的ip
#
import random
ips = dict()
# 将ip写入文件
with open("ips.txt", "w", buffering=1) as fp:
    for i in range(120000):
        fp.write("172.25.254.")
        x = random.randint(0, 255)
        x = str(x)
        fp.write(x)
        fp.write("\n")

# 统计频率前10的ip
with open('ips.txt', 'r') as fp:
    for ip in fp:

        # 出掉ip末尾的回车符
        ip = ip[:-1]

        # ip在ips中 数目加1；
        # 否则，数目为1
        if ip in ips:
            ips[ip] += 1
        else:
            ips[ip] = 1

#将ip值和数值交换顺序
#对频率前10的ip降序排序
top10 = sorted(ips.items(),key=lambda x:(x[1],x[0]),reverse=True)[:10]
print(top10,end='')


########2
# 访客：编写一个程序，提示用户输入其名字；用户作出响应后，将其名字写入到文件guest.txt中
# def input_name():
#     print("按q退出")
#     username = input("请输入用户名:")
#     if username == 'q':
#         print("输入结束")
#     else:
#         with open("guest.txt", "w", buffering=1) as fp:
#             fp.write(username)
#             fp.write("\n")
#
#
# input_name()

#########3
# 生成100个MAC地址并写入文件中，MAC地址前6位（16进制）为01-AF-3B

# def creat_MAC(x):
#     import random
#
#     lst = ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F']
#     for i in range(x):
#         with open("MAC.txt", "a", buffering=1) as fp:
#             fp.write("01-AF-3B-")
#             for j in range(3):
#                 if j == 2:
#                     MAC = ''.join(random.sample(lst, 2))
#                     fp.write(MAC)
#                 else:
#                     MAC = ''.join(random.sample(lst, 2))
#                     fp.write(MAC)
#                     fp.write("-")
#
#             fp.write("\n")
#
#
# x = int(input("请输入生成MAC地址的个数："))
# creat_MAC(x)


##########4
# 已经有一个瓦尔登湖的文本，“Walden.txt”
# 统计这篇文章的词频（每个词出现的次数）
# 不统计标点符号
# the和The被统计成同一个词（不区分大小写）
# 输出格式：（‘the’：10，'is':45...）
#
# import string
# import collections
#
# with open("Walden.txt",encoding="utf-8") as fp:
#     fp = fp.read()
#     # fp = fp.lower().split(' ')
#     for i in fp:
#         if i in string.punctuation:  # 如果字符是标点符号的话就将其替换为空格
#             fp = fp.replace(i, "")
#     fp = fp.lower().split(' ')
#     r=collections.Counter(fp)
#     print(r)

